package com.xiaolanshu.controller;


import com.xiaolanshu.entity.Dataurl;
import com.xiaolanshu.service.DataurlService;
import com.xiaolanshu.service.NoteService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/release")
public class ReleaseController {

    @Autowired
    private DataurlService dataurlService;
    @Autowired
    private NoteService noteService;

    /**
     * 上传笔记
     * @param param
     * @return
     */
    @PostMapping("/note")
    public ResponseEntity releaseNote(@RequestBody Map param){
        //保存笔记信息,并返回主键id
        Long noteId= noteService.saveNote(param);

        //如果上传的是视频，获取参数中的视频url并保存
        String videoUrl = (String) param.get("videourl");
        if(videoUrl != null){
            //根据笔记id保存视频信息
            Dataurl dataurlVideo = new Dataurl();
            dataurlVideo.setVideourl(videoUrl);
            dataurlVideo.setNoteId(noteId);
            dataurlService.saveVideo(dataurlVideo);
        }

        //如果上传的是图片，获取参数中的图片url列表并保存
        List<String> pictureUrl = (List<String>) param.get("pictureurl");
        if (pictureUrl != null){
            //图片有多张，所以遍历保存
            for (String s:pictureUrl
                 ) {
                //根据笔记id保存图片信息
                Dataurl dataurlPicture = new Dataurl();
                dataurlPicture.setPictureurl(s);
                dataurlPicture.setNoteId(noteId);
                dataurlService.savePicture(dataurlPicture);
            }
        }
        return ResponseEntity.status(200).body("上传成功");
    }

    /**
     * 上传视频
     * @param video
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadVideo")
    public ResponseEntity uploadVideo(MultipartFile video) throws Exception {
        //将视频上传到阿里云oss，并返回视频的url地址
        String videourl = dataurlService.uploadVideo(video);
       return ResponseEntity.ok(videourl);
    }

    /**
     * 上传图片
     * @param pictureList
     * @return
     * @throws Exception
     */
    @PostMapping("/uploadPicture")
    public ResponseEntity uploadPicture(List<MultipartFile> pictureList) throws Exception {

        //请求参数中的图片为集合，所以遍历取出
        List<String> pictureurlList = new ArrayList<>();
        for (MultipartFile s:pictureList
             ) {
            String pictureurl = dataurlService.uploadPicture(s);
            pictureurlList.add(pictureurl);
        }
        
        return ResponseEntity.ok(pictureurlList);
    }
}
